//
//  SABatchPurchaseDetailVC.m
//  saasRetail
//
//  Created by mac on 2022/9/15.
//

#import "SABatchPurchaseDetailVC.h"
#import "SASalesInvoiceListAPI.h"
#import "SABatchPurchaseDetailCell.h"
#import "SABatchPurchaseDetailHeaderView.h"
#import "SABatchPurchaseDetailFooterView.h"
#import "SAOcrScanResultModel.h"
#import "SASearchSupplierView.h"
#import "SASupplierModel.h"
#import "GFAlertView.h"
#import "ABatchPurchaseDetailSetPriceView.h"
#import "SAAddSupplierView.h"
#import "NSString+FintCommon.h"
#import "SAOcrCreateOrPurchaseProductAPI.h"

@interface SABatchPurchaseDetailVC ()<UITableViewDelegate, UITableViewDataSource, HTTPAPIDelegate, UITextFieldDelegate>

@property (nonatomic, strong) UITableView *tableView;
@property (nonatomic, strong) UITextField *supplierTf;
@property (nonatomic, strong) UILabel *totalLab;
@property (nonatomic, strong) SAOcrCreateOrPurchaseProductAPI *ocrBatchCreateProductAPI;
@property (nonatomic, strong) SASupplierModel *supplierModel;
@property (nonatomic, strong) UITextField *remarkTf;
@property (nonatomic, strong) UIButton *cancelBtn;

@end

@implementation SABatchPurchaseDetailVC

- (void)viewDidLoad {
    [super viewDidLoad];
    
}

#pragma mark - HTTPAPIDelegate
- (void)fetchData:(id)data fromServerSuccessedWithAPI:(HTTPAPI *)api {
    if (self.ocrBatchCreateProductAPI == api) {
        [Prompt popPromptViewWithMsg:@"添加成功" duration:2];
        [self.navigationController popViewControllerAnimated:YES];
    }
}

- (void)fetchDataFromServerFailedWithError:(NSError *)error API:(HTTPAPI *)api {
    
}


#pragma mark - UITableView Delegate & DataSource
-(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    return self.dataMarr.count;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return self.dataMarr[section].skuList.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    WeakSelf
    SABatchPurchaseDetailCell *cell = [tableView dequeueReusableCellWithIdentifier:@"SABatchPurchaseDetailCell" forIndexPath:indexPath];
    OcrSkuModel *model = self.dataMarr[indexPath.section].skuList[indexPath.row];
    cell.model = model;
    cell.changeNumBlock = ^{
        [weakSelf totalCount];
    };
    return cell;
}

-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    
}

-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    return kScaleNum(41);
}

- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section {
    
    SABatchPurchaseDetailHeaderView *header = [tableView dequeueReusableHeaderFooterViewWithIdentifier:@"SABatchPurchaseDetailHeaderView"];
    header.indexLab.text = [NSString stringWithFormat:@"%zd",section];
    SAOcrScanResultModel *model = self.dataMarr[section];
    header.model = model;
    header.indexLab.text = [NSString stringWithFormat:@"%zd",section + 1];
    WeakSelf
    header.deleteBlock = ^{
        [weakSelf.dataMarr removeObject:model];
        [tableView reloadData];
        [weakSelf totalCount];
    };
    header.changePriceBlock = ^{
        [weakSelf totalCount];
    };
    return header;
}

- (UIView *)tableView:(UITableView *)tableView viewForFooterInSection:(NSInteger)section {
    WeakSelf
    SABatchPurchaseDetailFooterView *footer = [tableView dequeueReusableHeaderFooterViewWithIdentifier:@"SABatchPurchaseDetailFooterView"];
    footer.addBlock = ^{
        OcrSkuModel *model = [OcrSkuModel new];
        [weakSelf.dataMarr[section].skuList addObject:model];
        [tableView reloadData];
    };
    return footer;
}

-(CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section {
    SAOcrScanResultModel *model = self.dataMarr[section];
    if (model.skuList.count > 0) {
        return kScaleNum(368);
    }
    return kScaleNum(328);
}

-(CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section {
    return kScaleNum(41);
}

- (BOOL)tableView:(UITableView *)tableView canEditRowAtIndexPath:(NSIndexPath *)indexPath {
    return YES;
}

-(NSArray<UITableViewRowAction*>*)tableView:(UITableView *)tableView editActionsForRowAtIndexPath:(NSIndexPath *)indexPath {
    WeakSelf
    OcrSkuModel *model = self.dataMarr[indexPath.section].skuList[indexPath.row];
    UITableViewRowAction *rowAction = [UITableViewRowAction rowActionWithStyle:UITableViewRowActionStyleDefault
                                                                         title:@"删除" handler:^(UITableViewRowAction * _Nonnull action, NSIndexPath * _Nonnull indexPath) {
        NSMutableArray *skuList = self.dataMarr[indexPath.section].skuList;
        [skuList removeObject:model];
        [tableView reloadData];
        [weakSelf totalCount];
    }];
    rowAction.backgroundColor = kPinkColor;
    NSArray *arr = @[rowAction];
    return arr;
}

- (NSString *)tableView:(UITableView *)tableView titleForDeleteConfirmationButtonForRowAtIndexPath:(NSIndexPath *)indexPath{
    return @"删除";
}

#pragma mark - UITextFieldDelegate
- (BOOL)textFieldShouldBeginEditing:(UITextField *)textField {
    [self clickedVipBtn];
    return false;
}

#pragma mark - event
-(void)clickedSetBtn {
    
    [self.view endEditing:YES];
    WeakSelf
    ABatchPurchaseDetailSetPriceView *view = [[ABatchPurchaseDetailSetPriceView alloc] initWithFrame:CGRectMake(0, 0, kScreenWidth, kScreenHeight)];
    view.multipleBlock = ^(NSString *retailMultiple, NSString *microStoreMultiple) {
        CGFloat retail = [retailMultiple floatValue];
        CGFloat microStore = [microStoreMultiple floatValue];
        for (SAOcrScanResultModel *model in weakSelf.dataMarr) {
            if ([model.productIsExist isEqualToString:@"1"]) {
                continue;
            }
            if (retailMultiple.length > 0) {
                model.retailPrice = [NSString stringWithFormat:@"%0.2lf",[model.price doubleValue] * retail];
            }
            if (microStoreMultiple.length > 0) {
                model.microStorePrice = [NSString stringWithFormat:@"%0.2lf",[model.price doubleValue] * microStore];
            }
        }
        [weakSelf totalCount];
        [weakSelf.tableView reloadData];
    };
    [self.view addSubview:view];
}

-(void)tipConfirm {
    GFAlertView *alertView = [GFAlertView alertViewWithMsg:@"提示" detailMsg:@"请确认已核对入库商品及SKU信息" leftBtnBlock:^(UIButton *leftBtn) {
        [leftBtn setTitle:@"再次确认" forState:UIControlStateNormal];
    } rightBtnBlock:^(UIButton *rightBtn) {
        [rightBtn setTitle:@"确认采购" forState:UIControlStateNormal];
        [rightBtn setTitleColor:kBuleColor forState:UIControlStateNormal];
        [rightBtn addTarget:self action:@selector(clickedConfirmBtn) forControlEvents:UIControlEventTouchUpInside];
    }];
    [alertView showWithAnimation];
}

-(void)clickedConfirmBtn {
    if (self.dataMarr.count == 0) {
        [Prompt popPromptViewWithMsg:@"请添加商品" duration:2];
        return;
    }
    
    NSInteger num = 0;
    double total = 0.0;
    
    NSMutableDictionary *batchCreateProductForm = [NSMutableDictionary dictionary];
    NSMutableDictionary *mdic = [NSMutableDictionary dictionary];
    batchCreateProductForm[@"batchCreateProductForm"] = mdic;

    NSMutableArray *ocrScanResultList = [[NSMutableArray alloc] init];
    
    for (SAOcrScanResultModel *model in self.dataMarr) {
        if (model.productName.length == 0) {
            [Prompt popPromptViewWithMsg:@"商品名称不能为空" duration:2];
            return;
        }
        
        
        NSMutableDictionary *productDic = [[NSMutableDictionary alloc] init];
        NSArray *imgUrls = [NSArray array];
        if (model.imgUrl.length > 0) {
            imgUrls = [model.imgUrl componentsSeparatedByString:@","];
        }
        productDic[@"imgUrls"] = imgUrls;
        productDic[@"price"] = [NSString stringWithFormat:@"%0.lf",[model.price doubleValue] * 100];
        productDic[@"productName"] = model.productName;
        productDic[@"retailPrice"] = [NSString stringWithFormat:@"%0.lf",[model.retailPrice doubleValue] * 100];
        productDic[@"microStorePrice"] = [NSString stringWithFormat:@"%0.lf",[model.microStorePrice doubleValue] * 100];
        if (model.productCode.length > 0) {
            productDic[@"productCode"] = model.productCode;
        }else {
            productDic[@"productCode"] = [self generateProductCode:model.productName];
        }
        if ([model.productIsExist isEqualToString:@"1"]) {
            productDic[@"productIsExist"] = @"1";
        }else {
            productDic[@"productIsExist"] = @"0";
        }
        
        NSMutableArray *skuList = [[NSMutableArray alloc] init];
        if (model.skuList.count > 0) {
            for (OcrSkuModel *sku in model.skuList) {
                if (sku.colorName.length == 0) {
                    [Prompt popPromptViewWithMsg:@"颜色名称不能为空" duration:2];
                    return;
                }
                if (sku.sizeName.length == 0) {
                    [Prompt popPromptViewWithMsg:@"此码名称不能为空" duration:2];
                    return;
                }
                
                NSMutableDictionary *skuDic = [[NSMutableDictionary alloc] init];
                skuDic[@"colorName"] = sku.colorName;
                skuDic[@"count"] = [NSString stringWithFormat:@"%zd", [sku.count integerValue]];
                skuDic[@"sizeName"] = sku.sizeName;
                num += [sku.count integerValue];
                total += [sku.count integerValue] * [model.price doubleValue];
                [skuList addObject:skuDic];
            }
        }else {
            NSMutableDictionary *skuDic = [[NSMutableDictionary alloc] init];
            skuDic[@"colorName"] = @"均色";
            skuDic[@"count"] = @"0";
            skuDic[@"sizeName"] = @"均码";
            [skuList addObject:skuDic];
        }

        productDic[@"ocrSkuForms"] = skuList;
        [ocrScanResultList addObject:productDic];
    }
    
    mdic[@"ocrProductForms"] = ocrScanResultList;

    if (self.supplierModel != nil) {
        mdic[@"providerName"] = self.supplierModel.providerName;
        mdic[@"providerId"] = self.supplierModel.providerId;
    }
    
    mdic[@"remark"] = self.remarkTf.text;
    mdic[@"slowCount"] = [NSString stringWithFormat:@"%zd",self.dataMarr.count];
    mdic[@"itemCount"] = [NSString stringWithFormat:@"%zd", num];
    mdic[@"totalAmount"] = [NSString stringWithFormat:@"%0.lf",total * 100];
    
    self.ocrBatchCreateProductAPI.coverParameters = mdic;
    [self.ocrBatchCreateProductAPI sendRequestToServerWithActivityViewAndMask:POST];
}

-(void)clickedVipBtn {
    [self.view endEditing:YES];
    SASearchSupplierView *searchSupplierView = [SASearchSupplierView shareCornView];
    UIViewController *vc = nil;
    [searchSupplierView showView:vc];
    WeakSelf
    searchSupplierView.selectBlock = ^(SASupplierModel * _Nonnull supplierModel) {
        if (supplierModel.mobile.length > 0) {
            weakSelf.supplierTf.text = [NSString stringWithFormat:@"%@(%@)",supplierModel.providerName,supplierModel.mobile];
        }else {
            weakSelf.supplierTf.text = supplierModel.providerName;
        }
        weakSelf.supplierModel = supplierModel;
        weakSelf.cancelBtn.hidden = NO;
    };
}

-(void)totalCount {
    if (self.dataMarr.count > 0) {
        NSInteger num = 0;
        double total = 0.0;
        for (SAOcrScanResultModel *model in self.dataMarr) {
            for (OcrSkuModel *sku in model.skuList) {
                NSInteger count = [sku.count integerValue];
                num += count;
                total += count * [model.price doubleValue];
            }
        }
        self.totalLab.text = [NSString stringWithFormat:@"合计：%zd款,%zd件,%0.2lf元",self.dataMarr.count,num,total];
    }else {
        self.totalLab.text = @"合计：";
    }
}

-(void)clickedAddGoodsBtn {
    SAOcrScanResultModel *model = [SAOcrScanResultModel new];
    model.skuList = [NSMutableArray array];
    if (self.dataMarr.count > 0) {
        [self.dataMarr insertObject:model atIndex:0];
    }else {
        [self.dataMarr addObject:model];
    }
    [self.tableView scrollToRowAtIndexPath:[NSIndexPath indexPathForRow:0 inSection:0] atScrollPosition:UITableViewScrollPositionTop animated:NO];
    [self.tableView reloadData];
    [self totalCount];
}

-(void)clickedCancelBtn {
    self.supplierTf.text = @"";
    self.cancelBtn.hidden = YES;
}

-(void)clickedAddBtn {
    SAAddSupplierView *addSupplierView = [SAAddSupplierView shareCornView];
    [addSupplierView showView:self];
}

- (UIImage *)imageMaskWithColor {

    UIImage *oldImage = [UIImage imageNamed:@"tabbar_select_5"];
    UIImage *newImage = nil;

    CGRect imageRect = (CGRect){CGPointZero,oldImage.size};
    UIGraphicsBeginImageContextWithOptions(imageRect.size, NO, oldImage.scale);

    CGContextRef context = UIGraphicsGetCurrentContext();
    CGContextScaleCTM(context, 1.0, -1.0);
    CGContextTranslateCTM(context, 0.0, -(imageRect.size.height));

    CGContextClipToMask(context, imageRect, oldImage.CGImage);//选中选区 获取不透明区域路径
    CGContextSetFillColorWithColor(context, [UIColor whiteColor].CGColor);//设置颜色
    CGContextFillRect(context, imageRect);//绘制

    newImage = UIGraphicsGetImageFromCurrentImageContext();//提取图片

    UIGraphicsEndImageContext();
    return newImage;
}

- (NSString *)generateProductCode:(NSString *)productName {
    static int kNumber = 7;
    NSString *sourceStr = @"0123456789";
    NSMutableString *resultStr = [[NSMutableString alloc] init];
    srand((unsigned)time(0));
    for (int i = 0; i < kNumber; i++)
    {
        unsigned index = rand() % [sourceStr length];
        NSString *oneStr = [sourceStr substringWithRange:NSMakeRange(index, 1)];
        [resultStr appendString:oneStr];
    }
    NSString *index = [productName charactorGetFirstCharactor:YES];
    if (![self validateNumber:index]) {
        index = @"A";
    }
    NSString *newStr = [NSString stringWithFormat:@"%@%@",index,resultStr];
    return newStr;
}

- (BOOL)validateNumber:(NSString*)number {
    BOOL res = YES;
    NSCharacterSet* tmpSet = [NSCharacterSet characterSetWithCharactersInString:@"/ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz012345678\\9*-"];
    int i = 0;
    while (i < number.length) {
        NSString * string = [number substringWithRange:NSMakeRange(i, 1)];
        NSRange range = [string rangeOfCharacterFromSet:tmpSet];
        if (range.length == 0) {
            res = NO;
            break;
        }
        i++;
    }
    return res;
}

#pragma mark - initUI
-(void)initUI {
    
    [self setNavigationItemBackBBIAndTitle:@"商品信息"];
    [self setBgImage:nil];
    
    UIButton *setBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    setBtn.frame = CGRectMake(0, 0, kScaleNum(60), kScaleNum(44));
    [setBtn setImage:[self imageMaskWithColor] forState:UIControlStateNormal];
    [setBtn addTarget:self action:@selector(clickedSetBtn) forControlEvents:UIControlEventTouchUpInside];
    [self addRightViews:@[setBtn]];
    
    UILabel *supplierTitleLab = [[UILabel alloc] initWithFrame:SARectMake(20, StatusHeight + 1, 60, 40)];
    supplierTitleLab.text = @"供货商：";
    supplierTitleLab.textColor = kBlackColor;
    supplierTitleLab.font = kFont(15);
    [self.view addSubview:supplierTitleLab];
    
    UITextField *supplierTf = [[UITextField alloc] initWithFrame:SARectMake(90, StatusHeight + 1, 190, 40)];
    supplierTf.placeholder = @"请选择供货商";
    supplierTf.textColor = kBlackColor;
    supplierTf.font = kFont(15);
    supplierTf.delegate = self;
    [self.view addSubview:supplierTf];
    self.supplierTf = supplierTf;
    
    UIButton *cancelBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    [cancelBtn setImage:[UIImage imageNamed:@"btn_cancle"] forState:UIControlStateNormal];
    cancelBtn.frame = SARectMake(280, StatusHeight + 1, 40, 40);
    cancelBtn.backgroundColor = [UIColor whiteColor];
    [cancelBtn addTarget:self action:@selector(clickedCancelBtn) forControlEvents:UIControlEventTouchUpInside];
    cancelBtn.hidden = YES;
    self.cancelBtn = cancelBtn;
    [self.view addSubview:cancelBtn];
    
    UIButton *addBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    [addBtn setImage:[UIImage imageNamed:@"codeAdd"] forState:UIControlStateNormal];
    addBtn.frame = SARectMake(320, StatusHeight + 1, 40, 40);
    addBtn.backgroundColor = [UIColor whiteColor];
    [addBtn addTarget:self action:@selector(clickedAddBtn) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:addBtn];
    
    UIView *line = [[UIView alloc] initWithFrame:SARectMake(0, StatusHeight + 41, kBaseScreenWidth, 1)];
    line.backgroundColor = kLineColor;
    [self.view addSubview:line];
    
    UILabel *remarkTitleLab = [[UILabel alloc] initWithFrame:SARectMake(20, StatusHeight + 42, 60, 40)];
    remarkTitleLab.text = @"备注：";
    remarkTitleLab.textColor = kBlackColor;
    remarkTitleLab.font = kFont(15);
    [self.view addSubview:remarkTitleLab];
    
    UITextField *remarkTf = [[UITextField alloc] initWithFrame:SARectMake(90, StatusHeight + 42, 275, 40)];
    remarkTf.placeholder = @"请输入备注信息";
    remarkTf.textColor = kBlackColor;
    remarkTf.font = kFont(15);
    [self.view addSubview:remarkTf];
    self.remarkTf = remarkTf;
    
    UIView *line2 = [[UIView alloc] initWithFrame:SARectMake(0, StatusHeight + 82, kBaseScreenWidth, 1)];
    line2.backgroundColor = kLineColor;
    [self.view addSubview:line2];
    
    UILabel *totalLab = [[UILabel alloc] initWithFrame:SARectMake(20, StatusHeight + 83, 260, 40)];
    totalLab.text = @"合计：";
    totalLab.textColor = kBlackColor;
    totalLab.font = kFont(15);
    [self.view addSubview:totalLab];
    self.totalLab = totalLab;
    
    UIButton *addGoodsBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    addGoodsBtn.frame = SARectMake(kBaseScreenWidth - 85, StatusHeight + 88, 80, 30);
    addGoodsBtn.backgroundColor = kBuleColor;
    [addGoodsBtn setTitle:@"添加商品" forState:UIControlStateNormal];
    addGoodsBtn.titleLabel.font = kFont(15);
    [addGoodsBtn setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
    addGoodsBtn.layer.cornerRadius = 5;
    addGoodsBtn.layer.masksToBounds = YES;
    [addGoodsBtn addTarget:self action:@selector(clickedAddGoodsBtn) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:addGoodsBtn];
    
    UIView *line3 = [[UIView alloc] initWithFrame:SARectMake(0, StatusHeight + 123, kBaseScreenWidth, 1)];
    line3.backgroundColor = kLineColor;
    [self.view addSubview:line3];
    
    [self.view addSubview:self.tableView];
    self.tableView.tableFooterView = [[UIView alloc] initWithFrame:SARectMake(0, 0, kScreenWidth, kScaleNum(40))];
    
    UIButton *confirmBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    confirmBtn.frame = CGRectMake(0, kScreenHeight - kScaleNum(40) - SafeFooterHeight, kScreenWidth, kScaleNum(40) + SafeFooterHeight);
    confirmBtn.titleLabel.font = kFont(16);
    [confirmBtn setTitle:@"确认采购" forState:UIControlStateNormal];
    [confirmBtn setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
    confirmBtn.backgroundColor = kBuleColor;
    [confirmBtn addTarget:self action:@selector(tipConfirm) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:confirmBtn];
    
    [self totalCount];
}

-(UITableView *)tableView {
    if (!_tableView) {
        _tableView = [[UITableView alloc] initWithFrame:CGRectMake(0, kScaleNum(StatusHeight + 124), kScreenWidth, kScreenHeight - kScaleNum(StatusHeight + 164) - SafeFooterHeight) style:UITableViewStyleGrouped];
        _tableView.backgroundColor = [UIColor whiteColor];
        _tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
        _tableView.delegate = self;
        _tableView.dataSource = self;
        _tableView.showsHorizontalScrollIndicator = NO;
        if (@available(iOS 11.0, *)) {
            _tableView.contentInsetAdjustmentBehavior = UIScrollViewContentInsetAdjustmentNever;
        }
        _tableView.estimatedRowHeight = 0;
        _tableView.estimatedSectionHeaderHeight = 0;
        _tableView.estimatedSectionFooterHeight = 0;
        [_tableView registerClass:[SABatchPurchaseDetailCell class] forCellReuseIdentifier:@"SABatchPurchaseDetailCell"];
        [_tableView registerClass:[SABatchPurchaseDetailHeaderView class] forHeaderFooterViewReuseIdentifier:@"SABatchPurchaseDetailHeaderView"];
        [_tableView registerClass:[SABatchPurchaseDetailFooterView class] forHeaderFooterViewReuseIdentifier:@"SABatchPurchaseDetailFooterView"];
    }
    return _tableView;
}

-(NSMutableArray<SAOcrScanResultModel *> *)dataMarr {
    if (!_dataMarr) {
        _dataMarr = [NSMutableArray array];
    }
    return _dataMarr;
}

-(SAOcrCreateOrPurchaseProductAPI *)ocrBatchCreateProductAPI {
    if (!_ocrBatchCreateProductAPI) {
        _ocrBatchCreateProductAPI = [SAOcrCreateOrPurchaseProductAPI apiWithDelegate:self];
    }
    return _ocrBatchCreateProductAPI;
}

@end
